package com.ict.txmsv2.controller.studentinfo;

import com.ict.txmsv2.exception.BadFileTypeException;
import com.ict.txmsv2.model.RespBean;
import com.ict.txmsv2.services.WordInfoService;
import com.ict.txmsv2.utils.WordDocUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Queue;

/**
 * @Author lht
 * @date 2021/9/24 - 17:55
 * @description: 上传学生信息的doc文档并从中读取消息导入数据库
 */
@RestController
@RequestMapping("/modifyWord")
@Api(tags = "上传学生信息的doc文档并从中读取消息导入数据库")
public class ModifyWordDocController {

    @Resource
    private WordInfoService wordInfoService;

    @PostMapping
    @ApiOperation(value = "导入学生信息Word文档到数据库中")
    public RespBean uploadWord(MultipartFile file) throws Exception {
        List<Queue<String>> list = WordDocUtils.handleWordInfo2List(file);
        if (wordInfoService.writeInfo2DB(list)) {
            return RespBean.ok("上传成功！");
        }
        return RespBean.error("上传失败！");
    }

    @GetMapping(produces = "application/octet-stream")
    @ApiOperation(value = "从数据库中导出学生信息到Word文档中")
    public void exportWordDoc(HttpServletResponse response) throws Exception {
        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader("content-type", "application/octet-stream");
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("工作室学生信息.docx", "UTF-8"));
        if (wordInfoService.downLoadWordDoc((outputStream))) {
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
        }
    }

    @GetMapping(value = "/template", produces = "application/octet-stream")
    @ApiOperation(value = "获取导入数据的Word文档模板")
    public void getWordTemplate(HttpServletResponse response) throws Exception {
        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader("content-type", "application/octet-stream");
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("工作室学生信息导入模板.docx", "UTF-8"));
        if (wordInfoService.getWordTemplate(outputStream)) {
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
        }
    }

}
